<template>
  <el-form :model="form" :rules="rules" ref="formRef">
    <!-- 动态表单项区域 -->
    <div v-for="(domain, index) in form.domains" :key="domain.key">
      <el-form-item
        label="姓名"
        :prop="`domains.${index}.name`"
        :rules="rules.name"
      >
        <el-input v-model="domain.name" placeholder="请输入姓名" />
      </el-form-item>

      <el-form-item
        label="年龄"
        :prop="`domains.${index}.age`"
        :rules="rules.age"
      >
        <el-input v-model.number="domain.age" placeholder="请输入年龄" />
      </el-form-item>

      <el-button 
        @click.prevent="removeDomain(domain)"
      >
        删除
      </el-button>
    </div>

    <!-- 添加按钮 -->
    <el-button @click="addDomain">添加新项</el-button>

    <!-- 提交按钮 -->
    <el-button type="primary" @click="submitForm">提交</el-button>
  </el-form>
</template>

<script setup>
import { ref, reactive } from 'vue'

const formRef = ref(null)
const form = reactive({
  domains: [
    { 
      key: Date.now(), // 唯一标识
      name: '',
      age: null 
    }
  ]
})

// 验证规则
const rules = reactive({
  name: [
    { required: true, message: '姓名不能为空', trigger: 'blur' }
  ],
  age: [
    { type: 'number', required: true, message: '年龄必须为数字', trigger: 'blur' }
  ]
})

// 添加表单项
const addDomain = () => {
  form.domains.push({
    key: Date.now(),
    name: '',
    age: null
  })
}

// 删除表单项
const removeDomain = (domain) => {
  const index = form.domains.indexOf(domain)
  if (index !== -1) {
    form.domains.splice(index, 1)
  }
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(valid => {
    if (valid) {
      console.log('提交数据：', form.domains)
    } else {
      console.log('验证失败')
      return false
    }
  })
}
</script>